package com.cci.kangdao.service.impl;

import com.cci.kangdao.azureBlob.AzureBlobTool;
import com.cci.kangdao.cipapi.CipServiceApi;
import com.cci.kangdao.dao.CourseTrainingDao;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.ServiceStationDao;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.ServiceStationService;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Description: 服务站相关信息业务
 * @Company: CTY
 * @author myc
 * @date 2018-02-27
 * @version 1.0
 */
@Service("serviceStationService")
public class ServiceStationServiceImpl implements ServiceStationService {
	private Logger log = Logger.getLogger(this.getClass().getName());

	@Resource
	private ServiceStationDao serviceStationDao;
	@Resource
	private LoginDao loginDao;
	@Resource
	private PropertiesUtils propertiesUtils;
	@Autowired
	private RedisClientUtils redisClientUtils;
	
	@Autowired
	private CRMPlatformServiceImpl cServiceImp;

	@Resource
	private XGJManagerServiceImpl xGJManagerServiceImpl;
	@Resource
	private CipServiceApi cipServiceApi;
	@Resource
	private CourseTrainingDao courseTrainingDao;

	/**
	 * 查询字典项所有数据
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getDictionaries(Map map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();			
			/**
			 * 1、首先看看redis是否存在字典项，不存在则查询数据库
			 */			
			List<DictionariesT> dictionariesList = (List<DictionariesT>)redisClientUtils.getObject("dictionariesList");
			if(dictionariesList == null || dictionariesList.size()==0){	
				//放入redis中
				dictionariesList = serviceStationDao.findDictionariesList(null);
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				redisClientUtils.setObject("dictionariesList", dictionariesList, redisCacheTime);
			}
			/**
			 * 查询机型类型
			 * 1、康明斯用户、游客用户：查询所有的机型。
			 * 2、JV用户：只能查看自己企业的机型
			 * 3、Dealer用户：根据Dealer用户所属服务站查询服务站对应的机型。
			 */
			List<EngineTypeT> engineTypeList = null;
			String userid = request.getHeader("userid");
			if(userid == null){
				engineTypeList = serviceStationDao.findEngineTypeList(null);
			}else{
				userid = AESTool.decryptString(userid);//解密userid
				UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
				if(userT == null){
					userT = loginDao.getUserByid(userid);
					if(userT == null){
						obj.put("status", -3);
						obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-3));
						
						//返回客户
						ParameterTool.writeResponse(response, obj.toString());	
						obj = null;
						return null;
					}
					int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
					redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);
				}
				/**
				 * 1 康明斯,2康明斯分公司,3 JV,4 OEM,5 SSOEM,6 Dealer,0	Engine Customer
				 */				
				if(userT.getIsType() ==1 || userT.getIsType() ==0){
					engineTypeList = serviceStationDao.findEngineTypeList(null);
				}else if(userT.getIsType() ==6){
					engineTypeList = serviceStationDao.findEngineTypeListByStation(""+userT.getServiceStationID());		
					
					/**
					 * 首先看看redis中是否存在enginType，如果不为null，看看类型长度是否相同
					 */
					String enginType = (String)redisClientUtils.getObject("enginType"+userid);
					if(enginType != null){
						if(engineTypeList.size() != enginType.split(",").length){
							redisClientUtils.delkey("enginType"+userid);
						}
					}
				}else{
					engineTypeList = serviceStationDao.findEngineTypeList(""+userT.getCompanyId());
				}
			}
			
			
			/**
			 * 2、将字典项内容返回给用户
			 */
			obj.put("status", 0);
			obj.put("msg", "");
			String dictionLabel = "";
			JSONObject content;	
			JSONArray jsonArray = null;
			for(DictionariesT  bean : dictionariesList){
				if(bean.getDtableName().trim().equals(dictionLabel)){					
					content = new JSONObject();	
					content.put("DInt", bean.getDInt());
					content.put("DValue", bean.getDvalue());
					jsonArray.put(content);
				}else{
					//如果字典项标签不等空则将数据放入到json
					if(!dictionLabel.trim().equals("")){
						obj.put(dictionLabel, jsonArray);
					}
					
					dictionLabel = bean.getDtableName();
					jsonArray = new JSONArray();
					content = new JSONObject();	
					content.put("DInt", bean.getDInt());
					content.put("DValue", bean.getDvalue());
					jsonArray.put(content);
				}				
			}
			obj.put(dictionLabel, jsonArray);
			
			/**
			 * 查询机型
			 */
			jsonArray = new JSONArray();
			for(EngineTypeT bean : engineTypeList){
				content = new JSONObject();	
				content.put("DInt", ""+bean.getId());
				content.put("DValue", bean.getTypename());
				jsonArray.put(content);
			}
			obj.put("EngineType", jsonArray);
			//获取标签
			List<Map<String, Object>> courseLabelList = courseTrainingDao.getCourseLabelList();
			obj.put("courseLabelList", courseLabelList);
			//学习状态
			List<Map<String,Object>> learnList = new ArrayList<>();
			Map<String,Object> oneMap = new HashMap<>();
			oneMap.put("DInt","1");
			oneMap.put("DValue","未开始（0%）");
			learnList.add(oneMap);
			Map<String,Object> twoMap = new HashMap<>();
			twoMap.put("DInt","2");
			twoMap.put("DValue","进行中（0-99%）");
			learnList.add(twoMap);
			Map<String,Object> threeMap = new HashMap<>();
			threeMap.put("DInt","3");
			threeMap.put("DValue","已完成（100%）");
			learnList.add(threeMap);
			obj.put("learnList", learnList);
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}
	
	/**
	 *查询所有服务站信息 
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView searchServiceStation(Map map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
							
			/**
			 * 1、获取用户的经纬度并解密
			 */
			if(map.get("position") == null  || map.get("position").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			String position = ""+map.get("position");
			position = AESTool.decryptString(position); //解密			
			int index = position.indexOf(",");
			map.put("lat", position.substring(0, index));
			map.put("lon", position.substring(index+1));
			
			if(map.get("searchTxt") != null && !map.get("searchTxt").toString().equals("")){
				map.put("searchTxt", "%"+map.get("searchTxt")+"%");
			}
			
			if(map.get("SSLevel") != null && !map.get("SSLevel").toString().equals("")){
				String SSLevel = ""+map.get("SSLevel");
				if(SSLevel.endsWith(",")){
					SSLevel =  SSLevel.substring(0, SSLevel.length()-1);
				}
//				if(SSLevel.contains(",")){
//					SSLevel = " in ("+SSLevel+")";
//				}else{
//					SSLevel = " ="+SSLevel;
//				}
				String[] split = SSLevel.split(",");
				java.util.ArrayList<String> stringList = new ArrayList<>(split.length);
				Collections.addAll(stringList,split);
				map.put("SSLevel", stringList);
			}
			
			if(map.get("SSType") != null && !map.get("SSType").toString().equals("")){
				String SSType = ""+map.get("SSType");
				if(SSType.endsWith(",")){
					SSType =  SSType.substring(0, SSType.length()-1);
				}
//				if(SSType.contains(",")){
//					SSType = " in ("+SSType+")";
//				}else{
//					SSType = " ="+SSType;
//				}
				String[] split = SSType.split(",");
				java.util.ArrayList<String> stringList = new ArrayList<>(split.length);
				Collections.addAll(stringList,split);
				map.put("SSType", stringList);
			}
			
			if(map.get("enginType") != null && !map.get("enginType").toString().equals("")){
				String[] split = map.get("enginType").toString().split(",");
				ArrayList<String> stringList = new ArrayList<>(split.length);
				Collections.addAll(stringList,split);
				map.put("enginType",stringList);
			}
			
			/**
			 * 查询用户身份
			 * 1 康明斯,2康明斯分公司,3 JV,4 OEM,5 SSOEM,6 Dealer,0	Engine Customer
			 */
			String userid = request.getHeader("userid");
			if(userid != null){
				userid = AESTool.decryptString(userid);//解密userid
				UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
				if(userT == null){
					userT = loginDao.getUserByid(userid);
					if(userT == null){
						obj.put("status", -3);
						obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-3));
						
						//返回客户
						ParameterTool.writeResponse(response, obj.toString());	
						obj = null;
						return null;
					}
					int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
					redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);
				}
				/**
				 * 1 康明斯,2康明斯分公司,3 JV,4 OEM,5 SSOEM,6 Dealer,0	Engine Customer
				 * 康明斯跟客户查询所有机型
				 * jv跟其他查询自己公司
				 * dealer查询自己机型 
				 */				
				if(userT.getIsType() ==1 || userT.getIsType() ==0){
					
				}else if(userT.getIsType() ==6){
					/**
					 * 如果enginType不为空就查询 dealer授权的所有机型
					 * 
					 */
					if(map.get("enginType") == null || map.get("enginType").toString().equals("")){
						String enginType = (String)redisClientUtils.getObject("enginType"+userid);
						if(enginType== null){
							enginType = "";
							List<EngineTypeT> engineTypeList = serviceStationDao.findEngineTypeListByStation(""+userT.getServiceStationID());
							for(EngineTypeT engineTypeT : engineTypeList){
								enginType += engineTypeT.getId()+",";
							}
							if(enginType.endsWith(",")){
								enginType = enginType.substring(0, enginType.length()-1);
							}
							int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
							redisClientUtils.setObject("enginType"+userid, enginType, redisCacheTime);
							if(enginType.equals("")){//如果服务站没有授权机型，赋值-1
//								map.put("enginType", " =-1");
								ArrayList<String> strings = new ArrayList<>();
								strings.add("-1");
								map.put("enginType", strings);
							}else{
//								if(enginType.contains(",")){
//									enginType =" in (" +enginType+")";
//								}else{
//									enginType = " ="+enginType;
//								}
								String[] split = enginType.split(",");
								ArrayList<String> strings = new ArrayList<>(split.length);
								Collections.addAll(strings,split);
								map.put("enginType", strings);
							}
						}else{
							if(enginType.equals("")){
//								map.put("enginType", " =-1");
								ArrayList<String> strings = new ArrayList<>();
								strings.add("-1");
								map.put("enginType", strings);
							}else{
//								if(enginType.contains(",")){
//									enginType =" in (" +enginType+")";
//								}else{
//									enginType = " ="+enginType;
//								}
//								map.put("enginType", enginType);
								String[] split = enginType.split(",");
								ArrayList<String> strings = new ArrayList<>(split.length);
								Collections.addAll(strings,split);
								map.put("enginType", strings);
							}
						}
					}			
					
				}else{
					map.put("companyID",""+userT.getCompanyId());
				}
			}
						
			/**
			 * 2、查询所有服务站信息
			 */		
			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
			/**
			 * 使用pagehelper分页报错
			 */
			//PageHelper.startPage(page, pagesize);
			map.put("page", (page-1)*pagesize);
			map.put("pagesize", pagesize);
			List<ServiceStationT> list = serviceStationDao.findServiceStation(map);
			
			/**
			 * 从redis中获取字典项的信息
			 * 如果redis中不存在，则重新放入
			 */
			Map<String, String> dictionariesMap = (Map<String, String>)redisClientUtils.getObject("dictionariesMap");
			if(dictionariesMap == null){
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				List<DictionariesT> dictionariesList = (List<DictionariesT>)redisClientUtils.getObject("dictionariesList");
				if(dictionariesList == null){
					//放入redis中
					dictionariesList = serviceStationDao.findDictionariesList(null);					
					redisClientUtils.setObject("dictionariesList", dictionariesList, redisCacheTime);
				}
				dictionariesMap = new HashMap<String, String>();
				for(DictionariesT bean : dictionariesList){
					dictionariesMap.put(bean.getDtableName()+bean.getDInt(), bean.getDvalue());
				}
				//放入redis中
				redisClientUtils.setObject("dictionariesMap", dictionariesMap, redisCacheTime);
			}
			
			/**
			 * 遍历服务站信息放入到用户中
			 */
			JSONArray ServiceStationJsonArray = new JSONArray();
			JSONObject content;	
			JSONArray jsonArray = null;
			List<SSRepairT> SSRepairList = null;
			List<EngineTypeT> engineTypeList = null;
			for(ServiceStationT ssBean : list){
				content =  new JSONObject();
//				"id": 1,
//				"stationName": "晨阳数控服务站",
//				"SSLevel": ["核心店", "销售一体"],
//				"province": "河北省",
//				"city": "石家庄市",
//				"area": "长安区",
//				"address": "中山路289号",
//				"distance": "1.5km",
//				"telephone": "400电话",
//				"phone": "15230897689",
//				"enginType": "ISF3.8、ISG2.8",
//				"position": "35.9873,116.2383",
//				"img": ["http://www.ad.d/a.png,http://www.ad.d/b.png", "http://www.ad.d/a.png,http://www.ad.d/b.png"],
//				"remark": "备注"
				
				content.put("id", AESTool.encryptString(ssBean.getId().toString()));
				content.put("stationName", ssBean.getStationname());
				content.put("province", ssBean.getProvince());
				content.put("city", ssBean.getCity());
				content.put("area", ssBean.getArea());
				content.put("address", ssBean.getAddress());
				content.put("distance", ssBean.getDistance());
				content.put("telephone", ssBean.getTelephone());
				content.put("phone", ssBean.getPhone());
				content.put("position", ssBean.getPositionLat()+","+ssBean.getPositionLon());
				content.put("remark", ssBean.getRemark());
				
				/**
				 * 获取服务站的级别SSLevel
				 * 根据服务站id查询服务站维修机型
				 * 根据服务站Id查询服务站图片
				 */
				//获取服务站的级别SSLevel
				SSRepairList = serviceStationDao.findSSRepair(ssBean.getId().toString());
				jsonArray = new JSONArray();
				JSONArray jsonArray1 = new JSONArray();//服务站类型
				for(SSRepairT ssRepairT : SSRepairList){
					String SSLevel = dictionariesMap.get("SSLevel"+ssRepairT.getSslevel());
					//去除null和去重
					if( SSLevel!= null && !jsonArray.toString().contains(SSLevel) ){
						jsonArray.put(SSLevel);
					}	
					String SSType = dictionariesMap.get("SSType"+ssRepairT.getSstype());
					//去除null和去重
					if( SSType!= null && !jsonArray1.toString().contains(SSType) ){
						jsonArray1.put(SSType);
					}
				}
				content.put("SSLevel", jsonArray);
				content.put("SSType", jsonArray1);
				SSRepairList.clear();
				SSRepairList = null;
				
				//根据服务站id查询服务站维修机型
				engineTypeList = serviceStationDao.findEngineType(ssBean.getId().toString());
				String engineTypeString = "";
				for(EngineTypeT engineTypeT : engineTypeList){
					engineTypeString += engineTypeT.getTypename()+"、";
				}
				if(engineTypeString.endsWith("、")){
					engineTypeString =  engineTypeString.substring(0, engineTypeString.length()-1);
				}
				content.put("enginType", engineTypeString);
				engineTypeList.clear();
				engineTypeList = null;
				
				//根据服务站Id查询服务站图片 
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				List<ServiceStationImgT> serviceStationImgList = (List<ServiceStationImgT>)redisClientUtils.getObject("serviceStationImg"+ssBean.getId());
				if(serviceStationImgList == null){
					serviceStationImgList = serviceStationDao.findServiceStationImg(ssBean.getId().toString());
					//放入redis中			
					redisClientUtils.setObject("serviceStationImg"+ssBean.getId(), serviceStationImgList, redisCacheTime);
				}
				jsonArray = new JSONArray();
				for(ServiceStationImgT serviceStationImgT : serviceStationImgList){
					jsonArray.put(serviceStationImgT.getImgurl());
				}
				content.put("img", jsonArray);
				serviceStationImgList.clear();
				serviceStationImgList = null;

				ServiceStationJsonArray.put(content);
			}		
			
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("serviceStations", ServiceStationJsonArray);
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}
	
	/**
	 * 获取我的服务站信息
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getMyServiceStation(Map map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
		
			/**
			 * 1、根据header中userid去redis获取userT
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
									
			if(userT.getServiceStationID() ==0){
				obj.put("status", -9);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-9));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
						
			/**
			 * 2、查询所有服务站信息
			 */		
			ServiceStationT ssBean = serviceStationDao.findServiceStationByID(""+userT.getServiceStationID());
			
			/**
			 * 从redis中获取字典项的信息
			 * 如果redis中不存在，则重新放入
			 */
			Map<String, String> dictionariesMap = (Map<String, String>)redisClientUtils.getObject("dictionariesMap");
			if(dictionariesMap == null){
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				List<DictionariesT> dictionariesList = (List<DictionariesT>)redisClientUtils.getObject("dictionariesList");
				if(dictionariesList == null){
					//放入redis中
					dictionariesList = serviceStationDao.findDictionariesList("");					
					redisClientUtils.setObject("dictionariesList", dictionariesList, redisCacheTime);
				}
				dictionariesMap =  new HashMap<String, String>();
				for(DictionariesT bean : dictionariesList){
					dictionariesMap.put(bean.getDtableName()+bean.getDInt(), bean.getDvalue());
				}
				//放入redis中
				redisClientUtils.setObject("dictionariesMap", dictionariesMap, redisCacheTime);
			}
			
			/**
			 * 3、将服务站信息拼成json
			 */
			JSONObject content;	
			JSONArray jsonArray = null;
			List<SSRepairT> SSRepairList = null;
			List<EngineTypeT> engineTypeList = null;
			content =  new JSONObject();			
			content.put("id", AESTool.encryptString(ssBean.getId().toString()));
			content.put("stationName", ssBean.getStationname());
			content.put("province", ssBean.getProvince());
			content.put("city", ssBean.getCity());
			content.put("area", ssBean.getArea());
			content.put("address", ssBean.getAddress());
			content.put("distance", ssBean.getDistance());
			content.put("telephone", ssBean.getTelephone());
			content.put("phone", ssBean.getPhone());
			content.put("position", ssBean.getPositionLat()+","+ssBean.getPositionLon());
			content.put("remark", ssBean.getRemark());
			
			/**
			 * 获取服务站的级别SSLevel
			 * 根据服务站id查询服务站维修机型
			 * 根据服务站Id查询服务站图片
			 */
			//获取服务站的级别SSLevel
			SSRepairList = serviceStationDao.findSSRepair(ssBean.getId().toString());
			jsonArray = new JSONArray();
			JSONArray jsonArray1 = new JSONArray();//服务站类型
			for(SSRepairT ssRepairT : SSRepairList){
				String SSLevel = dictionariesMap.get("SSLevel"+ssRepairT.getSslevel());
				//去除null和去重
				if( SSLevel!= null && !jsonArray.toString().contains(SSLevel) ){
					jsonArray.put(SSLevel);
				}	
				String SSType = dictionariesMap.get("SSType"+ssRepairT.getSstype());
				//去除null和去重
				if( SSType!= null && !jsonArray1.toString().contains(SSType) ){
					jsonArray1.put(SSType);
				}
			}
			content.put("SSLevel", jsonArray);
			content.put("SSType", jsonArray1);
			SSRepairList.clear();
			SSRepairList = null;
			
			//根据服务站id查询服务站维修机型
			engineTypeList = serviceStationDao.findEngineType(ssBean.getId().toString());
			String engineTypeString = "";
			for(EngineTypeT engineTypeT : engineTypeList){
				engineTypeString += engineTypeT.getTypename()+"、";
			}
			if(engineTypeString.endsWith("、")){
				engineTypeString =  engineTypeString.substring(0, engineTypeString.length()-1);
			}
			content.put("enginType", engineTypeString);
			engineTypeList.clear();
			engineTypeList = null;
			
			/**
			 * 从redis中根据服务站Id查询服务站图片 
			 */
			List<ServiceStationImgT> serviceStationImgList = getServiceStationImgRedis(""+ssBean.getId());
			jsonArray = new JSONArray();
			for(ServiceStationImgT serviceStationImgT : serviceStationImgList){
				jsonArray.put(serviceStationImgT.getImgurl());
			}
			content.put("img", jsonArray);
			serviceStationImgList.clear();
			serviceStationImgList = null;
			
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("serviceStations", content);
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}
	
	/**
	 * 修改服务站
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView updateMyServiceStation(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
		
			/**
			 * 1、服务站id，AES加密
			 */
			if(map.get("serviceStationId") == null  || map.get("serviceStationId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			//AES解密
			String serviceStationId = ""+map.get("serviceStationId");
			serviceStationId = AESTool.decryptString(serviceStationId);
			map.put("serviceStationId", serviceStationId);
			//ServiceStationT serviceStationT = serviceStationDao .findServiceStationByID(serviceStationId);
			//if(null != serviceStationT){
				map.put("hotLineOne", MapUtils.getString(map,"telephone",""));
				map.put("hotLineTwo", MapUtils.getString(map,"phone",""));
				map.put("detailedAddress", MapUtils.getString(map,"address",""));
			//}
			//拆分地理位置经纬度
			String position = MapUtils.getString(map,"position","");
			if(position.contains(",")){
				// 处理经纬度，保留6位小数
				DecimalFormat decimalFormat = new DecimalFormat("#,###.000000");
				String[] positions = position.split(",");
				String lat = positions[0];
				if(StringUtils.isNotEmpty(lat)){
					BigDecimal latDistance = new BigDecimal(lat);
					map.put("lat", decimalFormat.format(latDistance));
				}else{
					map.put("lat", "0.0");
				}
				String lon = positions[1];
				if(StringUtils.isNotEmpty(lon)){
					BigDecimal lonDistance = new BigDecimal(lon);
					map.put("lon", decimalFormat.format(lonDistance));
				}else{
					map.put("lon", "0.0");
				}
				map.put("address", MapUtils.getString(map,"address",""));
				map.put("province", MapUtils.getString(map,"province",""));
				String city = MapUtils.getString(map,"city","");
				if(city.equals("[]")){
					city = "";
				}
				map.put("city", city);
				String area = MapUtils.getString(map,"area","");
				if(area.equals("[]")){
					area = "";
				}
				map.put("area",area);
				
				/**
				 * 如果经纬度有更新需要同步给CRM系统
				 */
				try {
					cServiceImp.syncServiceStationLonAndLat(map);
				}catch (Exception e){
					log.error(e.getMessage(), e);
				}

			}
			
			/**
			 * 2、修改用户信息
			 */
			map.remove("response");
			int result = serviceStationDao.updateServiceStation(map);
			if(result>0){
				if (map.get("lat")!=null && map.get("lon")!=null){
					xGJManagerServiceImpl.updateXgjLocation(map);
				}
				obj.put("status", 0);
				obj.put("msg", "");
			}else{
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}		
			
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}
	
	/**
	 * 上传服务站图片
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView uploadServiceStationImg(Map map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();
			/**
			 * 1、服务站id，AES加密
			 */
			if(map.get("serviceStationId") == null  || map.get("serviceStationId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			//AES解密
			String serviceStationId = ""+map.get("serviceStationId");
			serviceStationId = AESTool.decryptString(serviceStationId);
			map.put("serviceStationId", serviceStationId);
			
			/**
			 * 2、开始上传文件
			 * 判断文件是否存在
			 */
//			String basePath = request.getSession().getServletContext().getRealPath("upload");
			String basePath = request.getSession().getServletContext().getRealPath(propertiesUtils.getPropertiesValue("upload").trim());
			File imgFile = new File(basePath);
			if(!imgFile.exists()){
				imgFile.mkdirs();
			}
			imgFile = null;
			map.put("basePath", basePath);
			
			String fileName = Upload_Util.uploadData(map);
			if(fileName == null  || fileName.equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			/**
			 * 上传到微软云存储文件
			 */
			String filePath = basePath + File.separator + fileName;
			fileName = AzureBlobTool.uploadBlob(propertiesUtils.getPropertiesValue("accountName").trim(),
					propertiesUtils.getPropertiesValue("blobConnection").trim(),
					propertiesUtils.getPropertiesValue("containerName").trim(),
					filePath);
			
			map.put("imgUrl", fileName);
			map.put("layer", 0);
			if (StringUtils.isNotEmpty(fileName)) {
				try {
					// 删除服务器文件
					FileUtils.forceDelete(new File(filePath));
				} catch (IOException e) {
					log.warn("删除服务器照片失败" + e.getMessage(), e);
				}
			}
			int result = serviceStationDao.insertServiceStationImg(map);
			if(result>0){
				obj.put("status", 0);
				obj.put("msg", "");
				obj.put("imgUrl", fileName);
				
				/**
				 * 删除redis中服务站数据，并重新更新服务站图片
				 */
				redisClientUtils.delkey("serviceStationImg"+serviceStationId);
				getServiceStationImgRedis(serviceStationId);
			}else{
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}		
			
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex){
			log.error(ex.getMessage(),ex);
		}
		return null;
	}
	
	/**
	 * 删除服务站图片
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView delServiceStationImg(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
		
			/**
			 * 1、服务站id，AES加密
			 */
			if(map.get("serviceStationId") == null  || map.get("serviceStationId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			if(map.get("imgUrl") == null  || map.get("imgUrl").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			//AES解密
			String serviceStationId = ""+map.get("serviceStationId");
			serviceStationId = AESTool.decryptString(serviceStationId);
			map.put("serviceStationId", serviceStationId);
			
			/**
			 * 2、删除服务站的图片信息
			 */
			map.remove("response");
			int result = serviceStationDao.updateServiceStationImg(map);
			if(result>0){
				/**
				 * 微软云存储账号删除图片信息
				 */
				String fileName = ""+map.get("imgUrl");
				fileName = fileName.substring(fileName.lastIndexOf("/")+1);
				AzureBlobTool.deleteBlob(propertiesUtils.getPropertiesValue("blobConnection").trim(),
						propertiesUtils.getPropertiesValue("containerName").trim(),
						fileName);
				/**
				 * 删除redis中服务站数据，并重新更新服务站图片
				 */
				redisClientUtils.delkey("serviceStationImg"+serviceStationId);
				getServiceStationImgRedis(serviceStationId);
				
				obj.put("status", 0);
				obj.put("msg", "");
			}else{
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}		
			
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}
	
	/**
	 * 获取服务站下属账号
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getServiceStationUser(Map map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
		
			/**
			 * 1、根据header中userid去redis获取userT
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
									
			if(userT.getServiceStationID() ==0){
				obj.put("status", -9);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-9));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
						
			/**
			 * 2、查询所有服务站信息
			 */		
			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
			/**
			 * 使用pagehelper分页报错
			 */
			PageHelper.startPage(page, pagesize);
			map.put("userId", userT.getId());
			map.put("serviceStationId", userT.getServiceStationID());
			List<UserT> userList = serviceStationDao.findServiceStationUserByID(map);
			JSONArray jsonArray = new JSONArray();
			JSONObject content;
			for(UserT userBean : userList){
//				//不属于自己的账号
//				if(userBean.getId() != userT.getId()){
					content =  new JSONObject();
//					"id": "DESSED",
//					"contact": "真实姓名",
//					"phone": "15230850726",
//					"systime": "2018-01-02 11:12:30"				
					content.put("id", AESTool.encryptString(""+userBean.getId()));
					content.put("contact", userBean.getContact());
					content.put("phone", userBean.getPhone());
					content.put("role", userBean.getPosition());
					content.put("systime", PublicTool.dateTimeChangeChina(userBean.getSystime().substring(0,19)));				
					jsonArray.put(content);
//				}				
			}
			
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("users", jsonArray);
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}
	
	/**
	 * 移除服务站下属账号 
	 * @param map
	 * @return
	 */
	@Override
	@Transactional
	public ModelAndView delServiceStationUser(Map map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
		
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//AES解密
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			
			/**
			 * 1、服务站id，AES加密
			 */
			if(map.get("serviceStationId") == null  || map.get("serviceStationId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			if(map.get("userId") == null  || map.get("userId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			//AES解密
			String serviceStationId = ""+map.get("serviceStationId");
			serviceStationId = AESTool.decryptString(serviceStationId);
			map.put("serviceStationId", serviceStationId);

			String userId = ""+map.get("userId");
			userId = AESTool.decryptString(userId);
			map.put("userId", userId);
			
			/**
			 * 2、 移除服务站下属账号 
			 */
			map.remove("response");
			
			// 获取用户原有角色
			String preRoles = getUserRoles(Long.parseLong(userId));
			
			/**
			 * 修改用户的默认用户组
			 */
			long usergroupID = Long.valueOf(propertiesUtils.getPropertiesValue("usergroupID"));
			map.put("usergroupID", usergroupID);
			int result = serviceStationDao.updateServiceStationUser(map);
			if(result>0){
				
				// 解除原用户角色关联
				loginDao.delUserRoleRel(userId);
				
				// 基本信息修改成功后，修改用户关联角色信息
                //2.8.0修复bug    之前普通用户组只有app终端用户角色所以原来sql没问题   之后多了很多角色
                // 导致站长删除下属账户   下属账户不光置为终端用户，还多了别的角色
                //这里换了个sql   只获取终端用户的角色
                List<Long> roles = loginDao.userGroupHasYHRole(usergroupID);
				
				for(int i = 0; i< roles.size(); i++) {
					Map<String,Object> paramsMap = new HashMap<String,Object>();
					paramsMap.put("userID", userId);
					paramsMap.put("rolesID", roles.get(i));
					loginDao.insertUserRole(paramsMap);
				}
				
				obj.put("status", 0);
				obj.put("msg", "");
				//技师删除同步芯管家服务站
				cipServiceApi.updateXgjFleetUserId(Long.valueOf(userId),Long.valueOf(serviceStationId));
				// 修改后用户角色
				String curRoles = getUserRoles(Long.parseLong(userId));
				
				// 记录删除日志
				map.put("uId", userT.getId());
				map.put("rolesPre", preRoles);
				map.put("rolesNow", curRoles);
				try{
					serviceStationDao.addScanRecord(map);
				} catch(Exception e) {
					log.error(map, e);
				}
				
				// 记录操作日志
				SystemLogsT systemLogsT = new SystemLogsT();
				systemLogsT.setUserId(userT.getId());
				systemLogsT.setTname("User_T");
				systemLogsT.setTid(Long.valueOf(userId));
				systemLogsT.setActionName("updateData");//操作方法
				systemLogsT.setRemark("修改用户");
				loginDao.insertSystemLogs(systemLogsT);
				
			}else{
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}		
			
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}	

	/**
	 * 更新redis中服务站图片信息
	 * @return
	 */
	private List<ServiceStationImgT> getServiceStationImgRedis(String serviceStationId){
		List<ServiceStationImgT> serviceStationImgList = (List<ServiceStationImgT>)redisClientUtils.getObject("serviceStationImg"+serviceStationId);
		if(serviceStationImgList == null){
			serviceStationImgList = serviceStationDao.findServiceStationImg(serviceStationId);
			//放入redis中			
			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
			redisClientUtils.setObject("serviceStationImg"+serviceStationId, serviceStationImgList, redisCacheTime);
		}
		return serviceStationImgList;
	}
	
	public String getUserRoles(Long userId) {
		List<Map<String, Object>> roleList = loginDao.getUserRoles(userId);
		StringBuffer sb = new StringBuffer();
		for(Map<String, Object> role: roleList) {
			sb.append("/").append(role.get("RolesName"));
		}
		return sb.toString().substring(1);
	}

	 /**
	  * @description:
	   * @param: null
	  * @return:
	  * @exception:
	  * @author: wunan
	  * @company: Pactera Technology Co.,Ltd
	  * @since: 2021/8/9 17:24
	  * @version: V1.0
	  */
	 public ModelAndView getServiceStationById(Map map) {
		 HttpServletResponse response = (HttpServletResponse)map.get("response");
		 Long id = Long.parseLong(MapUtils.getString(map, "id"));
		 Map<String,Object> serviceStation = serviceStationDao.getServiceStationById(id);
		 ParameterTool.writeSuccessResponse(response, serviceStation);
		 return null;
	 }
}
